package com.derbysoft.core.conveter;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.util.StrutsTypeConverter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;

public class DateConverter extends StrutsTypeConverter {

    private static Log logger = LogFactory.getLog(DateConverter.class);

    private static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";

    @SuppressWarnings("unchecked")
    @Override
    public Object convertFromString(Map context, String[] values, Class toClass) {
        String joined = StringUtils.join(values);
        if (StringUtils.isBlank(joined)) {
            return null;
        }
        try {
            return new SimpleDateFormat(DEFAULT_DATE_PATTERN).parse(joined);
        } catch (ParseException e) {
            logger.warn("Parsed date [" + joined + "] use pattern [" + DEFAULT_DATE_PATTERN + "]", e);
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public String convertToString(Map context, Object o) {
        return new SimpleDateFormat(DEFAULT_DATE_PATTERN).format(o);
    }
}
